package com.edu.koudingmusic.fragments;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;

import com.edu.koudingmusic.MainActivity;
import com.edu.koudingmusic.R;
import com.edu.koudingmusic.entities.SearchResult;
import com.edu.koudingmusic.tools.DownloadUtils;

public class DownloadDialogFragment extends DialogFragment {

    // 当前要下载的歌曲
    private SearchResult mSearchResult;
    private MainActivity mMainActivity;

    private String[] items;


    public DownloadDialogFragment() {
        // Required empty public constructor
    }

    public static DownloadDialogFragment newInstance(SearchResult searchResult) {
        DownloadDialogFragment fragment = new DownloadDialogFragment();
        fragment.mSearchResult = searchResult;
        return fragment;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) getActivity();
        items = new String[]{getString(R.string.download), getString(R.string.cancel)};
    }

    // 创建对话框的事件方法
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mMainActivity);
        builder.setCancelable(true);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        // 下载音乐
                        downloadMusic();
                        break;
                    case 1:
                        dialog.cancel();
                        break;
                }
            }
        });
        return builder.show();
    }

    // 下载音乐
    private void downloadMusic() {
        Toast.makeText(mMainActivity, "正在下载" + mSearchResult.getMusicName(), Toast.LENGTH_SHORT).show();

        DownloadUtils.getInstance().setListener(new DownloadUtils.OnDownloadListener() {
            @Override
            public void onDownload(String mp3Url) {
                //下载
                Toast.makeText(mMainActivity, "歌曲下载成功", Toast.LENGTH_SHORT).show();
                // 扫描新下载的歌曲
//                Uri contentUri = Uri.fromFile(new File(mp3Url));
//                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri);
//                getContext().sendBroadcast(mediaScanIntent);
            }

            @Override
            public void onFailed(String error) {
                // 下载失败
                Toast.makeText(mMainActivity, error, Toast.LENGTH_SHORT).show();
            }
        }).download(mSearchResult);
    }
}
